#include "Controller.h"
#include "mainwindow.h"
// Static variables statements
QString MainWindow::getPath;
QString MainWindow::savePath;
QString MainWindow::cameraPath;
QSignalMapper* MainWindow::signalMapper;
Controller::Controller(QObject *parent) : QObject(parent)
{
    //Distribute Multiple Signals from SignalMapper
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(imgLoad(const QString &)));
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(openCamera(const QString &)));
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(clearNum(const QString &)));
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(capture(const QString &)));
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(closeCamera(const QString &)));
    connect(MainWindow::signalMapper, SIGNAL(mapped (const QString &)),
            this, SLOT(imgSave(const QString &)));
}
void Controller::imgLoad(const QString &Text)
{
    if(Text=="OPEN")
    {
        this->Img = new QImage;
        Img->load(MainWindow::getPath);
        emit sendImg(Img);
        emit sendPath(MainWindow::getPath);
    }
}
void Controller::openCamera(const QString &Text)
{
    if(Text=="openCamera")
    {
        c.openCamera();
    }
}

void Controller::closeCamera(const QString &Text)
{
    if(Text=="closeCamera")
    {
        c.closeCamera();
    }
}

void Controller::clearNum(const QString &Text)
{
    if(Text=="savePath")
        captureNum=0;
}

void Controller::capture(const QString &Text)
{
    if(Text=="capture")
    {
        if(c.isAvailable())
        {
            if(!MainWindow::cameraPath.isEmpty())
            {
                captureNum++;
                Img=c.getPicture();
                QString filename = MainWindow::cameraPath+"/"+QString::number(captureNum)+".jpg";
                Img->save(filename);
                //Send Signals to ImageProcesser
                emit sendImg(Img);
                emit sendPath(filename);
            }
            else
                emit sendError("Please input camera's save path firstly!");
        }
        else
            emit sendError("Camera isn't available!");
    }
}

void Controller::imgSave(const QString &Text)
{
    if(Text=="save"&& Img!=NULL)
    {
        Img->save(MainWindow::savePath);
    }
}
